package his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import his.entity.CheckApply;
import his.entity.FmedItem;
import his.entity.MedicalRecord;
import his.entity.Patient;
import his.persistence.CheckApplyMapper;
import his.persistence.FmedItemMapper;
import his.persistence.MedicalRecordMapper;
import his.persistence.PatientMapper;
import his.service.FmedItem2Service;
import org.example.his.common.api.CommonResponse;
import org.example.his.common.auth.JwtAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FmedItem2ServiceImpl implements FmedItem2Service {
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    MedicalRecordMapper medicalRecordMapper;
    @Autowired
    CheckApplyMapper checkApplyMapper;
    @Autowired
    FmedItemMapper fmedItemMapper;

    @Override
    public CommonResponse<List<FmedItem>> check_manageDetailToFmeditem_get1(String token) {
        String openID = JwtAuth.jwtDecrypt(token);
        List<FmedItem> fmedItems = new ArrayList<>();

        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("OpenID", openID);
        String CaseNumber = patientMapper.selectOne(queryWrapper).getCaseNumber();
        QueryWrapper<MedicalRecord> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.like("CaseNumber", CaseNumber);
        List<MedicalRecord> medicalRecords = medicalRecordMapper.selectList(queryWrapper1);
        for (int i = 0; i < medicalRecords.size(); i++) {
            int RegistID = medicalRecords.get(i).getRegistID();
            int MedicalID = medicalRecords.get(i).getID();
            QueryWrapper<CheckApply> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("MedicalID", MedicalID);
            queryWrapper2.eq("RegistID", RegistID);
            List<CheckApply> checkApplyList = checkApplyMapper.selectList(queryWrapper2);
            for (int j = 0; j < checkApplyList.size(); j++) {
                QueryWrapper<FmedItem> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("ID", checkApplyList.get(j).getId());
                FmedItem fmedItems1 = fmedItemMapper.selectOne(queryWrapper3);
                fmedItems.add(fmedItems1);
            }
        }
        if (fmedItems.size() > 0)
            return CommonResponse.createForSuccess("查询成功", fmedItems);
        else
            return CommonResponse.createForError(1, "查询失败");
    }
}
